package com.cqfae.deploycentral.app.web.controller;

import com.cqfae.deploycentral.app.utils.GsonUtils;
import com.cqfae.deploycentral.app.base.BaseConstants;
import com.cqfae.deploycentral.app.dao.entity.FileSync;
import com.cqfae.deploycentral.app.services.CommonControllerService;
import com.cqfae.deploycentral.app.services.FileSyncDetailService;
import com.cqfae.deploycentral.app.services.FileSyncService;
import com.cqfae.deploycentral.app.utils.NullUtil;
import com.cqfae.deploycentral.app.web.request.FileSyncRequest;
import com.cqfae.deploycentral.app.web.response.WebResponse;
import com.cqfae.deploycentral.app.web.vo.FileSyncDetailVo;
import com.cqfae.deploycentral.app.web.vo.FileSyncFileVo;
import com.cqfae.deploycentral.app.web.vo.FileSyncVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * TAppInfo相关操作
 *
 * @author JIANGLU009
 * @since 1.0.0-snapshot
 */
@RestController
@RequestMapping("/deploy-central/file-sync")
public class FileSyncController implements CommonControllerService<Object> {

    private static Logger logger = LoggerFactory.getLogger(FileSyncController.class);

    @Autowired
    private FileSyncService fileSyncService;

    @Autowired
    private FileSyncDetailService fileSyncDetailService;

    /**
     * 新增
     *
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add")
    public WebResponse add(@RequestBody FileSyncVo vo) {
        String voJson = GsonUtils.getInstance().toJson(vo);
        logger.info("==== add FileSyncVo :==== {}", voJson);
        // 参数空验证
        parameterCheck(vo);
        // 新增数量
        int num = 0;
        if (vo.getFileSyncFileVo() != null && !vo.getFileSyncFileVo().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            for (FileSyncFileVo fileSyncFileVo : vo.getFileSyncFileVo()) {
                paremeterFileCheck(fileSyncFileVo.getFileName(), fileSyncFileVo.getFileType());
                FileSync fileSync = vo.parseModel();
                fileSync.setName(fileSyncFileVo.getFileId());
                fileSync.setType(fileSyncFileVo.getFileType());
                // 去除掉名字相同的文件上传
                if (!fileSyncFileVo.getFileType().equals(map.get(fileSyncFileVo.getFileId()))) {
                    num += fileSyncService.add(fileSync);
                    map.put(fileSyncFileVo.getFileId(), fileSyncFileVo.getFileType());
                }
            }
        } else {
            Assert.isTrue(false, "请至少上传一个文件");
        }

        return getWebResponse(num);
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/file/upload", method = RequestMethod.POST)
    public WebResponse fileUpload(@RequestParam("file") MultipartFile file) throws IOException {
        Assert.isTrue((file.getSize() > 0 && file.getSize() < BaseConstants.FILE_LIMIT_BYTES), "文件上传大小必须在1kb到10M之间");
        return getWebResponse(fileSyncService.fileUpload(file));
    }

    /**
     * 文件上传
     *
     * @param fileId
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/file/delete")
    public WebResponse fileDelete(String fileId) throws IOException {
        return getWebResponse(fileSyncService.fileDelete(fileId));
    }

    /**
     * 编辑
     *
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/edit")
    public WebResponse edit(@RequestBody FileSyncVo vo) {
        String voJson = GsonUtils.getInstance().toJson(vo);
        logger.info("==== edit FileSyncVo :==== {}", voJson);
        // 参数空验证
        parameterCheck(vo);
        return getWebResponse(fileSyncService.edit(vo.parseModel()));
    }

    /**
     * 删除
     *
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    public WebResponse delete(@RequestBody FileSyncVo vo) {
        String voJson = GsonUtils.getInstance().toJson(vo);
        logger.info("==== delete FileSyncVo :==== {}", voJson);
        return getWebResponse(fileSyncService.delete(vo.parseModel()));
    }

    /**
     * 翻页查询
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list-by-page")
    public WebResponse listByPage(FileSyncRequest request) {
        String requestJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== listByPage FileSyncRequest :==== {}", requestJson);
        return getWebResponse(fileSyncService.listByPage(request));
    }

    /**
     * 根据ID查询一个
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/get-one")
    public WebResponse getOne(FileSyncRequest request) {
        String requestJson = GsonUtils.getInstance().toJson(request);
        logger.info("====  getOne FileSyncRequest :==== {}", requestJson);
        return getWebResponse(fileSyncService.getOne(request));
    }

    /**
     * 详情新增
     *
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/detail-add")
    public WebResponse detailAdd(@RequestBody FileSyncDetailVo vo) {
        String voJson = GsonUtils.getInstance().toJson(vo);
        logger.info("==== detailAdd FileSyncDetailVo :==== {}", voJson);
        // 参数空验证
        detailParameterCheck(vo);
        return getWebResponse(fileSyncDetailService.add(vo.parseModel()));
    }

    /**
     * 回调详情新增
     *
     * @param vo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/detail/call-back")
    public WebResponse detailCallBack(FileSyncDetailVo vo) {
        String voJson = GsonUtils.getInstance().toJson(vo);
        logger.info("==== detailNotify FileSyncDetailVo :==== {}", voJson);
        // 参数空验证
        detailCallBackParameterCheck(vo);
        return getWebResponse(fileSyncDetailService.detailCallBack(vo));
    }

    /**
     * 详情查询
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/detail-list")
    public WebResponse detailList(FileSyncRequest request) {
        String requestJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== detailList FileSyncRequest :==== {}", requestJson);
        return getWebResponse(fileSyncDetailService.list(request));
    }

    /**
     * 文件同步
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/file-sync")
    public WebResponse fileSync(FileSyncRequest request) {
        String requestJson = GsonUtils.getInstance().toJson(request);
        logger.info("==== fileSync FileSyncRequest :==== {}", requestJson);
        return getWebResponse(fileSyncService.fileSync(request));
    }

    /**
     * 设置返回参数
     *
     * @param obj
     * @return
     */
    @Override
    public WebResponse getWebResponse(Object obj) {
        WebResponse webResponse = new WebResponse();
        if (NullUtil.isNotEmpty(obj)) {
            webResponse.setData(obj);
        }
        return webResponse;
    }

    /**
     * 传入参数验证
     *
     * @param vo
     */
    private void parameterCheck(FileSyncVo vo) {
        Assert.isTrue(!StringUtils.isEmpty(vo.getAreaCode()), "区域类型为空");
        Assert.isTrue(!StringUtils.isEmpty(vo.getInteriorAreaCode()), "内网区域为空");
    }

    private void paremeterFileCheck(String name, String typeCode) {
        Assert.isTrue(!StringUtils.isEmpty(name), "文件名称为空");
        Assert.isTrue(!StringUtils.isEmpty(typeCode), "文件类型为空");
    }

    /**
     * 详情传入参数验证
     *
     * @param vo
     */
    private void detailParameterCheck(FileSyncDetailVo vo) {
        Assert.isTrue(vo.getFileSyncId() != null, "同步ID为空");
        Assert.isTrue(!StringUtils.isEmpty(vo.getTargetArea()), "目标区域为空");
        Assert.isTrue(!StringUtils.isEmpty(vo.getTargetIp()), "目标IP为空");
        Assert.isTrue(!StringUtils.isEmpty(vo.getTargetContent()), "目标目录为空");
        Assert.isTrue(!StringUtils.isEmpty(vo.getSyncTime()), "同步时间为空");
        Assert.isTrue(!StringUtils.isEmpty(vo.getStatusCode()), "同步状态为空");
    }

    /**
     * 详情传入参数验证
     *
     * @param vo
     */
    private void detailCallBackParameterCheck(FileSyncDetailVo vo) {
        Assert.isTrue(!StringUtils.isEmpty(vo.getArea()), "目标区域为空");
        Assert.isTrue(!StringUtils.isEmpty(vo.getZone()), "内网区域为空");
        Assert.isTrue(!StringUtils.isEmpty(vo.getTargetIp()), "目标IP为空");
        Assert.isTrue(!StringUtils.isEmpty(vo.getTargetContent()), "目标目录为空");
        Assert.isTrue(!StringUtils.isEmpty(vo.getTime()), "同步时间为空");
        Assert.isTrue(!StringUtils.isEmpty(vo.getStatus()), "同步状态为空");
    }

}
